import React, { useEffect, useState } from 'react';
import Form from '@knownsec/react-component/dist/Form';
import Input from '@knownsec/react-component/dist/Input';
import Button from '@knownsec/react-component/dist/Button';
import Textarea from '@knownsec/react-component/dist/Textarea';
import Message from '@knownsec/react-component/dist/Message';
import recursion from '../../../helpers/recursionFormJob';
import CheckboxTree from '../../../components/CheckboxTree';
import ContentCard from '../../../components/ContentCard';
import fetchFer from 'API/fetch';
import cn from 'classnames';
import s from './style.module.css';
import Radio from '@knownsec/react-component/dist/Radio';

function vulTempSettings({ location }) {
	const custom_profile_template_id = React.useMemo(
		() =>
			new URLSearchParams(location.search).get('custom_profile_template_id') ||
			'',
		[location]
	);
	const data = {
		name: '',
		description: '',
		plugin_list: {},
	};
	const [form] = Form.useForm();
	const validatormap = (rule, value) => {
		if (rule.field === 'name' && !value) {
			return Promise.reject('请输入模板名称');
		}
		if (rule.field === 'name' && value && value.length > 50) {
			return Promise.reject('模板名称不能超过50字符');
		}
		if (rule.field === 'description' && value && value.length > 100) {
			return Promise.reject('模板描述不能超过100字符');
		}
		if (rule.field === 'plugin_list' && !Object.keys(value).length) {
			return Promise.reject('请选择漏洞');
		}
		return Promise.resolve();
	};
	const [isSubmit, setIsSubmit] = useState(false);
	const submitForm = () => {
		form.validateFields().then(async result => {
			const data = form.getFieldValue();
			setIsSubmit(true);
			const res = await fetchFer(
				`/api/v2/kb/${custom_profile_template_id ? 'update' : 'save'}_profile`,
				{
					method: 'POST',
					body: JSON.stringify(
						custom_profile_template_id
							? {
									...data,
									plugin_list: Object.values(data.plugin_list).flat(),
									custom_profile_template_id,
							  }
							: { ...data, plugin_list: Object.values(data.plugin_list).flat() }
					),
					checkStatus: 501,
				}
			).catch(err => {
				return err;
			});
			if (res.code === 200) {
				Message.show({
					type: 'success',
					message: '操作成功',
					onclose() {
						window.location.href =
							'/#/policy-manage/vul-template-settings/list';
						setIsSubmit(false);
					},
				});
			} else {
				Message.show({
					type: 'error',
					message: res.msg || res.message || '操作失败',
				});
				setIsSubmit(false);
			}
		});
	};
	const updateFormData = async () => {
		const res = await fetchFer(`api/v2/kb/get_custom_profile`, {
			method: 'POST',
			body: JSON.stringify({ custom_profile_template_id }),
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		if (res.code === 200) {
			form.setFieldsValue(res.data);
		}
	};
	useEffect(() => {
		if (custom_profile_template_id) {
			updateFormData();
		}
		return () => {
			setIsSubmit(false);
		};
	}, []);
	return (
		<ContentCard
			bread={{
				arr: [
					{ link: 'policy-manage/vul-template-settings', name: '综合管理' },
					{ link: 'list', name: '漏洞模板' },
					{
						link: '',
						name: custom_profile_template_id ? '编辑' : '新增',
						active: true,
					},
				],
			}}
			content={
				<div className={s.p24}>
					<Form
						form={form}
						pro
						initialValues={data}
						className={s.vulTempForm}
						onValuesChange={(newItem, allValues) => {
							const val = recursion(newItem);
							form.setFieldsValue(val);
						}}
						labelAlign="right"
						labelCol={{ span: 2 }}
						wrapperCol={{ span: 22 }}
					>
						<Form.Item
							label="模板名称"
							name="name"
							rules={[{ required: true, validator: validatormap }]}
						>
							<Input
								className={s.w360}
								placeholder="请输入模板名称，不超过50字符"
								pro
								inline
							/>
						</Form.Item>
						<Form.Item
							label="模板描述"
							name="description"
							rules={[{ validator: validatormap }]}
						>
							<Textarea
								row={3}
								placeholder="请输入模板描述，不超过100字符"
								className={cn(s.textarea, s.w360)}
							/>
						</Form.Item>
						<Form.Item
							label="监测场景"
							name="scene_type"
							rules={[{ validator: validatormap }]}
						>
							<Radio.Group>
								<Radio className={s.h24} value={'web'}>
									web监测
								</Radio>
								<Radio
									refs="taskTriggerTypeManual"
									className={cn(s.ml24, s.h24)}
									value={'host'}
								>
									主机监测
								</Radio>
							</Radio.Group>
						</Form.Item>
						<Form.Item
							label="选择漏洞"
							name="plugin_list"
							rules={[{ required: true, validator: validatormap }]}
						>
							<CheckboxTree />
						</Form.Item>
					</Form>
					<div className="tac">
						<Button type="plain" onClick={() => window.history.back()}>
							取消
						</Button>
						<Button
							type="primary"
							htmlType="submit"
							disabled={isSubmit}
							style={{ position: 'relative', top: '-1px', marginLeft: '24px' }}
							onClick={submitForm}
						>
							提交
						</Button>
					</div>
				</div>
			}
		/>
	);
}

export default vulTempSettings;
